package task

import (
	"codedef"
	"log"
	//"message"
)

type TaskMgr struct {
	tasks map[string]*Task
}

var (
	Mgr = &TaskMgr{}
)

func sendTaskStatus2User(ntype string, status string, t *Task) {
	//message.SendNotification(t.account, msgNotifyJSON)
}

func (mgr *TaskMgr) executeTask(t *Task) {
	mgr.tasks[t.id] = t
	sendTaskStatus2User("/taskstatus", "run", t)
	t.execute()
	delete(mgr.tasks, t.id)
	sendTaskStatus2User("/taskstatus", "stop", t)
}

func (mgr *TaskMgr) StartTask(account string, taskId string) int {
	t, ok := mgr.tasks[taskId]
	if ok {
		log.Println("StartTask failed, task already start, id:", taskId)
		return codedef.ERR_TASK_ALREADY_START
	}

	var errc int = 0
	t, errc = loadTask(taskId)

	if t == nil {
		log.Println("StartTask failed, load task return nil")
		return errc
	}

	t.account = account

	go mgr.executeTask(t)

	return codedef.ERR_SUCCEED
}

func (mgr *TaskMgr) StopTask(account string, taskId string) int {
	t, ok := mgr.tasks[taskId]
	if !ok {
		log.Println("StopTask failed, task not running, id:", taskId)
		return codedef.ERR_TASK_NOT_RUNNING
	}

	if t.account != account {
		log.Println("StopTask failed, account not match")
		return codedef.ERR_TASK_NOT_BELONG2_ACCOUNT
	}

	if t.cancelAble && t.chanCancel != nil {
		t.chanCancel <- true
	} else {
		log.Println("StopTask failed, task not cancelable, id:", taskId)
		return codedef.ERR_TASK_NOT_CANCEL_ABLE
	}

	return codedef.ERR_SUCCEED
}

func (mgr *TaskMgr) IsTaskRunning(taskId string) bool {
	_, ok := mgr.tasks[taskId]
	return ok
}

func init() {
	Mgr.tasks = make(map[string]*Task)
}
